<?php
/**
 * $Id: controller.php 28 2010-10-07 16:11:28Z ahmtsari $
 * bfauction default controller
 *
 * @package    Joomla
 * @subpackage Components
 * @link http://www.tamlyncreative.com.au/software
 * @copyright	Copyright (c) 2010 - Tamlyn Creative Pty Ltd.
 * @license		GNU GPL
 *
 *	  BF Auction is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    BF Auction is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with BF Auction.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Author's notes: When GNU speaks of free software, it is referring to freedom, not price.
 * We encourage you to purchase your copy of BF Auction from the developer (Tamlyn Creative Pty Ltd),
 * so that we can continue to make this product better and continue to provide a high quality of support.
 *
 */

jimport('joomla.application.component.controller');

/**
 * bfauction Component Controller
 *
 * @package    Joomla
 * @subpackage Components
 */
class bfauctionController extends JController
{
	/**
	 * Method to display the view
	 *
	 * @access	public
	 */
	function display()
	{		
		parent::display();
	}

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_bfauction', $msg );
	}

	function bid()
	{
		JRequest::setVar( 'view', 'bid' );
		JRequest::setVar( 'layout', 'default'  );

		parent::display();
	}
	
	function bidHistory()
	{
		JRequest::setVar( 'view', 'bidhistory' );
		JRequest::setVar( 'layout', 'default'  );

		parent::display();
	}	
	
	function listItems()
	{
		JRequest::setVar( 'view', 'bfauction' );
		JRequest::setVar( 'layout', 'default'  );

		parent::display();
	}	

	function mybid()
	{
		global $mainframe;
		$itemId 		= JRequest::getVar( 'cid', 0, '', 'int' );
		$bid 			= JRequest::getVar( 'bid', 0, '', 'int' );
		
    	$Itemid = JRequest::getVar('Itemid');
		$menu =& JMenu::getInstance('site');
		$config = & $menu->getParams( $Itemid );	

		$bidIncrement = $config->get( 'bidIncrement' );
		$currency = $config->get( 'currency' );
		$dst_fix = $config->get( 'dst' );
		
		if ($itemId==0 | $bid < 1)
		{
			JError::raiseWarning( 500, 'There was an error processing your bid.' );
			$msg="";
			$this->setRedirect( 'index.php?option=com_bfauction&task=listItem', $msg );
		} else {
			$user =& JFactory::getUser();
			
			// is dst on on that particular date ?
  			if (is_numeric( $date)) 
  			{
				$ts = $date;
  			} else {
    			$ts = strtotime( $date . ' UTC');
  			}
  			$dst = date( 'I', $ts);
  			
  			$now =& JFactory::getDate();
  			if($dst_fix){
				$now->setOffset($user->getParam('timezone')+$dst);
  			}else{
  				$now->setOffset($user->getParam('timezone'));
  			}
			$currentDate=$now->toFormat();
			
			$db			=& JFactory::getDBO();
			
			$query = 'SELECT *'
	  			. ' FROM #__bfauction AS a'
	  			. ' WHERE a.published = 1 and a.id='.(int)$itemId.''
	  			. ' ORDER BY a.title'
	  			;
	  			
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum())
			{
				echo $db->stderr();
				return false;
			}
			$myresult=&$rows[0];
			
			if ($currentDate > $myresult->endDate)
			{
				JError::raiseWarning( 500, 'Bid not accepted as auction has now ended.' );
				$msg="";
				$this->setRedirect( 'index.php?option=com_bfauction&task=listItems&Itemid='.$Itemid, $msg );
			} else {
				if ($bid > ($myresult->currentBid + ((int)$bidIncrement-1)) )
				{
					/*
						AS100922
					*/
					if ($this->isBidPayed($itemId, $bid))
					{
						$db			=& JFactory::getDBO();
						$query = 'UPDATE #__bfauction SET'
							. ' currentBid='.$bid.' ,highBidder='.$db->quote( $db->getEscaped($user->name), false ).' '
		  					. ' WHERE id ='.(int)$itemId.''
		  					;
		  					
						$db->setQuery( $query );
						if (!$db->query())
						{
							echo $db->getErrorMsg();
							return false;
						}
	
						$query = 'INSERT INTO #__bfbid (`itemid`, `username`, `bid`, `bid_time`)'
							. ' VALUES ('.(int)$itemId.', '.$db->quote( $db->getEscaped($user->name), false ).', '.(int)$bid.',  "'.$currentDate.'")'
		  					;
	
						$db->setQuery( $query );
						if (!$db->query())
						{
							echo $db->getErrorMsg();
							return false;
						}
		  					
						$msg = JText::_( 'Bid confirmed' );
					} else {
						return false;
					}
					
				} else {
					JError::raiseWarning( 500, 'Bid not accepted as it is lower than the current highest bid.' );
					$msg="";
					$this->setRedirect( 'index.php?option=com_bfauction&task=listItems&Itemid='.$Itemid, $msg );
				}
			}	  			
		}
		$this->setRedirect( 'index.php?option=com_bfauction&task=listItems&Itemid='.$Itemid, $msg );
	}
	
    function getItem($itemId)
    {
       	$db			=& JFactory::getDBO();
			
		$query = 'SELECT *'
	  			. ' FROM #__bfauction AS a'
				. ' WHERE a.id ='.(int)$itemId.''
	  			;
	  			
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum())
		{
			echo $db->stderr();
			return false;
		}

		return $rows;
    }    
    
    function getPreviousBidder($itemId)
    {
       	$db			=& JFactory::getDBO();

		$query = ' SELECT * FROM #__bfbid '
				. '  WHERE `itemid` = '.(int)$itemId.''
				. ' ORDER BY bid_time desc'
	  			;
	  			
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum())
		{
			echo $db->stderr();
			return false;
		}

		//last be should be second element in array
		if(count($rows) > 1 ){
			return $rows;
		}else{
			return null;
		}
    }      
    
	function myitems()
	{
		JRequest::setVar( 'view', 'myitems' );
		JRequest::setVar( 'layout', 'default'  );

		parent::display();
	}    
    
	function item()
	{
		JRequest::setVar( 'view', 'item' );
		JRequest::setVar( 'layout', 'form'  );

		parent::display();
	}

	/**
	* Publishes one or more modules
	*/
	function publishQuestion(  ) {
		bfauctionController::changePublishQuestion( 1 );
	}

	/**
	* Unpublishes one or more modules
	*/
	function unPublishQuestion(  ) {
		bfauctionController::changePublishQuestion( 0 );
	}

	/**
	* Publishes or Unpublishes one or more modules
	* @param integer 0 if unpublishing, 1 if publishing
	*/
	function changePublishQuestion( $publish )
	{
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$db 		=& JFactory::getDBO();
		$user 		=& JFactory::getUser();

		$cid		= JRequest::getVar('cid', array(), '', 'array');
		$option		= JRequest::getCmd('option');
		JArrayHelper::toInteger($cid);

		if (empty( $cid )) {
			JError::raiseWarning( 500, 'No items selected' );
			$mainframe->redirect( 'index.php?option='. $option );
		}

		$cids = implode( ',', $cid );

		$query = 'UPDATE #__bfauction'
		. ' SET published = '.(int) $publish
		. ' WHERE id IN ( '. $cids .' )'
		. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $user->get('id') .' ) )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}

		$mainframe->redirect( 'index.php?option='. $option );
    }


/**
* Moves the record up one position
*/
function moveUpQuestion(  ) {
	bfauctionController::orderQuestion( -1 );
}

/**
* Moves the record down one position
*/
function moveDownQuestion(  ) {
	bfauctionController::orderQuestion( 1 );
}

/**
* Moves the order of a record
* @param integer The direction to reorder, +1 down, -1 up
*/
function orderQuestion( $inc )
{
	global $mainframe;

	// Check for request forgeries
	//JRequest::checkToken() or jexit( 'Invalid Token' );

    JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_bfauction'.DS.'tables');
	$row =& JTable::getInstance('item', 'Table');

	$db		=& JFactory::getDBO();
	$cid	= JRequest::getVar('cid', array(0), '', 'array');
	$option = JRequest::getCmd('option');
	JArrayHelper::toInteger($cid, array(0));

	$limit 		= JRequest::getVar( 'limit', 0, '', 'int' );
	$limitstart = JRequest::getVar( 'limitstart', 0, '', 'int' );
	$catid 		= JRequest::getVar( 'catid', 0, '', 'int' );

	$row =& JTable::getInstance( 'item', 'Table' );
	$row->load( $cid[0] );
	$row->move( $inc, 'catid = '.(int) $row->catid.' AND published != 0' );

	$mainframe->redirect( 'index.php?option='. $option );
}

function saveOrder( )
{
	$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
	global $mainframe;

	// Check for request forgeries
	JRequest::checkToken() or jexit( 'Invalid Token' );

	// Initialize variables
	$db			=& JFactory::getDBO();
	$order 		= JRequest::getVar( 'order', array(0), 'post', 'array' );
	$total		= count( $cid );
	JArrayHelper::toInteger($order, array(0));

	$row =& JTable::getInstance('item', 'Table');
	$groupings = array();

	// update ordering values
	for( $i=0; $i < $total; $i++ ) {
		$row->load( (int) $cid[$i] );
		// track categories
		$groupings[] = $row->catid;

		if ($row->ordering != $order[$i]) {
			$row->ordering = $order[$i];
			if (!$row->store()) {
				JError::raiseError(500, $db->getErrorMsg() );
			}
		}
	}

	// execute updateOrder for each parent group
	$groupings = array_unique( $groupings );
	foreach ($groupings as $group){
		$row->reorder('catid = '.(int) $group);
	}

	$msg 	= 'New ordering saved';
	$mainframe->redirect( 'index.php?option=com_bfauction', $msg );
}

	/**
	 * display the edit form
	 * @return void
	 */
	function edit()
	{
		JRequest::setVar( 'view', 'item' );
		JRequest::setVar( 'layout', 'form'  );
		JRequest::setVar('hidemainmenu', 1);

		parent::display();
	}

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		$model = $this->getModel('item');

		if ($model->store($post)) {
			$msg = JText::_( 'Record Saved!' );
		} else {
			$msg = JText::_( 'Error Saving Record' );
		}

		$msg = $cid[0];

		// Check the table in so it can be edited.... we are done with it anyway
		$link = 'index.php?option=com_bfauction';
		$this->setRedirect($link, $msg);
	}

	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
		$model = $this->getModel('item');
		if(!$model->delete()) {
			$msg = JText::_( 'Error: One or More Auction Items Could not be Deleted' );
		} else {
			$msg = JText::_( 'Auction item(s) Deleted' );
		}

		$this->setRedirect( 'index.php?option=com_bfauction', $msg );
	}
	
	/**
	  Copies one or more item
	 */
	function copy()
	{
		// Check for request forgeries
		//JRequest::checkToken() or jexit( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_bfauction' );

		$cid	= JRequest::getVar( 'cid', null, 'post', 'array' );
		$db		=& JFactory::getDBO();

		$table	=& JTable::getInstance('item', 'Table');

		$user	= &JFactory::getUser();
		$n		= count( $cid );

		if ($n > 0)
		{
			foreach ($cid as $id)
			{
				if ($table->load( (int)$id ))
				{
				   $table->id					= "";
					$table->title				= 'Copy of ' . $table->title;
					$table->published 			= 0;
					$table->ordering 			= 0;

					$now =& JFactory::getDate();
					$table->date			= $now->toMySQL();

					if (!$table->store()) {
						return JError::raiseWarning( $table->getError() );
					}
				}else{
					return JError::raiseWarning( 500, $table->getError() );
			    }
			}
		}else{
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}
		$this->setMessage( JText::sprintf( 'Items copied', $n ) );
	}
	
	/*
		Author: AS100922
	*/
	function isBidPayed($itemId = 0, $bid = 0)
	{
        $user =& JFactory::getUser();
        $userid = $user->get('id');

        $query = "SELECT * FROM #__alpha_userpoints
            WHERE userid = " . $userid ;
        $db =& JFactory::getDBO();
        $db->setQuery( $query );
        if (!$row = $db->loadObject()) {
            JError::raiseError(1, $db->getError());
        }
        if ($row->points < 2) {
    		JError::raiseWarning(0, JText::_('Bid not accepted as your credit lower than bid fee.') );
    		$msg="";
    		JError::raiseWarning(0, JText::sprintf( 'Your rest credit is', $row->points ) );
    		$this->setRedirect( 'index.php?option=com_bfauction&task=listItems&Itemid='.$itemId, $msg );
			return false;
		} elseif ($row->points < $bid) {
    		JError::raiseWarning(0, JText::_('Bid not accepted as it is lower than your usable credit.') );
    		$msg="";
    		JError::raiseWarning(0, JText::sprintf( 'Your rest credit is', $row->points ) );
    		$this->setRedirect( 'index.php?option=com_bfauction&task=listItems&Itemid='.$itemId, $msg );
			return false;
 		} else {
       		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_alphauserpoints'.DS.'tables');
    		$ptsTbl =& JTable::getInstance('userspoints');
    		if (!$ptsTbl->load($row->id)) {
              JError::raiseError(2, "id = ".$row->id." - ".$ptsTbl->getError());
            }
    		$ptsTbl->points = $row->points - 2;
    		if (!$ptsTbl->store(true)) {
                JError::raiseError(3, $ptsTbl->getError());
    			//echo "<script> alert('".$ptsTbl->getError()."'); window.history.go(-1); </script>\n";
    			return false;
            }
		}
		return true;
	}
	
    
}
?>
